//
//  SendStatusViewController.swift
//  weibopush
//
//  Created by 龚欣 on 15/7/6.
//  Copyright © 2015年 gong. All rights reserved.
//

import UIKit
import FFAutoLayout
import SVProgressHUD

class SendStatusViewController: UIViewController,UITextViewDelegate {

    var toolbarBottomConstraint : NSLayoutConstraint?
    
    override func loadView() {
        view = UIView(frame: UIScreen.mainScreen().bounds)
        
        addChildViewController(photoSelectVC)
        view.addSubview(photSelectView)
        
        setUpUI()
    }
    
    ///  MARK: 添加表情控制器
    func setUpEmoticon(){
        addChildViewController(emoticonVC)
        
    }
    
    
    ///  MARK: 设置UI
    func setUpUI(){
        automaticallyAdjustsScrollViewInsets = false
        
        setNaviBar()
        setUpEmoticon()
        prepareTextView()
        prepareToolbar()
        prepareOther()
    }
    
    func setNaviBar(){
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        navigationItem.rightBarButtonItem?.enabled = false
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        let titleView = UIView(frame: CGRectMake(0, 0, 100, 40))
        let label1 = UILabel(color: UIColor.darkGrayColor(), fonSize: 14)
        label1.text = "发微博"
        titleView.addSubview(label1)
        
        let label2 = UILabel(color: UIColor.lightGrayColor(), fonSize: 13)
        label2.text = sharedAccount?.name
        titleView.addSubview(label2)
        
        label1.ff_AlignInner(ff_AlignType.TopCenter, referView: titleView, size: nil)
        label2.ff_AlignInner(ff_AlignType.BottomCenter, referView: titleView, size: nil)
        
        navigationItem.titleView = titleView
        
    }

    
    func prepareTextView(){
        view.addSubview(textView)
        textView.ff_AlignInner(ff_AlignType.TopLeft, referView: view, size: nil)
        textView.ff_AlignVertical(ff_AlignType.TopRight, referView: photSelectView, size: nil)
        textView.alwaysBounceVertical = true
        textView.addSubview(placeHoldLabel)
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        textView.font = UIFont.systemFontOfSize(18)
        textView.contentInset = UIEdgeInsets(top: 64, left: 0, bottom: 0, right: 0)
        textView.delegate = self
        placeHoldLabel.ff_AlignInner(ff_AlignType.TopLeft, referView: textView, size: nil, offset: CGPoint(x: 6, y: 5))
        view.addSubview(lengthLabel)
        lengthLabel.ff_AlignInner(ff_AlignType.BottomRight, referView: textView, size: nil)
        lengthLabel.text = "\(140 - textView.text.characters.count)"
    }
    
    func prepareToolbar(){
        toolbar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        var items = [UIBarButtonItem]()
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "choosePhoto"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        for itemSetting in itemSettings {
            items.append(UIBarButtonItem(imageName: itemSetting["imageName"]!, imageName_highlighted: nil, target: nil, ActionName: itemSetting["action"]))
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        toolbar.items = items
        view.addSubview(toolbar)
        
        let cons = toolbar.ff_AlignInner(ff_AlignType.BottomLeft, referView: view, size: nil)
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[toolbar]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["toolbar" : toolbar]))
        
        toolbarBottomConstraint = toolbar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)

    }
    
    func prepareOther(){
        photSelectView.ff_AlignVertical(ff_AlignType.TopCenter, referView: toolbar, size: nil)
        view.addConstraint(NSLayoutConstraint(item: photSelectView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Width, multiplier: 1.0, constant: 0))
        view.addConstraint(NSLayoutConstraint(item: photSelectView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 100))
        photSelectView.hidden = true
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        textView.becomeFirstResponder()
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        textView.resignFirstResponder()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        view.backgroundColor = UIColor.whiteColor()
    }
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    func choosePhoto(){
        print(__FUNCTION__)
        photSelectView.hidden = !photSelectView.hidden
    }
    
    
    // MARK: 切换表情键盘
    func inputEmoticon(){
        
        //切换键盘需要先关闭键盘
        textView.resignFirstResponder()
        
        textView.inputView =  textView.inputView == nil ? emoticonVC.view : nil
        
        textView.becomeFirstResponder()
    }
    private let statusLength = 140
    // MARK: textView代理方法
    func textViewDidChange(textView: UITextView) {
        placeHoldLabel.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        //注意 由于一个表情不是一个字符所以这里不能使用textView.text而应该使用
        lengthLabel.text = "\(statusLength - textView.emoticonText().characters.count)"
        lengthLabel.textColor = statusLength - textView.emoticonText().characters.count > 0 ? UIColor.darkGrayColor() : UIColor.redColor()
        
    }
    
    func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    //  MARK: 点击发送
    func sendStatus(){
        print(textView.emoticonText())
        if textView.emoticonText().characters.count > statusLength {
            SVProgressHUD.showInfoWithStatus("字数超过上限")
        }
        
        SVProgressHUD.show()
        let image = photoSelectVC.imageArray.last
        NetworkTool.sharedNetworkTool().sendStatus(textView.emoticonText(), image: image) { (error) -> () in
            SVProgressHUD.dismiss()
            if error != nil {
                SVProgressHUD.showErrorWithStatus("您的网络不给力")
                return
            }
            self.close()
        }
    }
    
    
    
    /// 本地键盘切换标记 - 以下函数专用 真机调试没有UIKeyboardIsLocalUserInfoKey 这个KEY!!!!!!模拟器调试的时候有！！！！！！！！！！！！
    private var localKeyboardFlag = false
    ///  MARK: 键盘改变时候通知
    func keyboardChange(note : NSNotification){
        
        let rect = note.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        var duration = note.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        toolbarBottomConstraint?.constant = -(view.bounds.height - rect.origin.y)
        
         // 取 UIKeyboardIsLocalUserInfoKey，如果为0，不做动画
        if let local = note.userInfo!["UIKeyboardIsLocalUserInfoKey"]?.boolValue{
            if !local{
                localKeyboardFlag = true
                return
            }
        }
        //由于在转换键盘的时候一定要先收起键盘再弹出键盘，对于时间非常短的键盘调整，要把动画时间设成0
        duration = localKeyboardFlag ? 0 : duration
        
        UIView.animateWithDuration(duration) {
            self.view.layoutIfNeeded()
        }
        
    }

    lazy var emoticonVC : EmoticonViewController = EmoticonViewController {[unowned self] (emoticon) -> () in
        self.textView.insertEmoticon(emoticon)
    }
    
    lazy var textView  = UITextView()
    private lazy var placeHoldLabel : UILabel = {
        let label = UILabel(color: UIColor.grayColor(), fonSize: 15)
        label.text = "分享新鲜事...."
        return label
        }()
    private lazy var rightBaritem = UIBarButtonItem()
    private lazy var toolbar : UIToolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: 0, height: 44))
    private lazy var lengthLabel : UILabel = UILabel(color: UIColor.redColor(), fonSize: 12)
    private lazy var photoSelectVC : PhotoSelectViewController = PhotoSelectViewController()
    private lazy var photSelectView : UIView = self.photoSelectVC.view
}
